package com.hjw.logtest1.controller;

import com.hjw.logtest1.error.BusinessException;
import com.hjw.logtest1.error.EmBusinessError;
import com.hjw.logtest1.response.CommonReturnType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class BaseController {

    //参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonReturnType handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setCode(EmBusinessError.PARAMMETER_VALIDATION_ERROR.getErrCode());
        commonReturnType.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        return commonReturnType;
    }

    //参数校验异常
    @ExceptionHandler(BindException.class)
    public CommonReturnType handleBindException(BindException e) {
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setCode(EmBusinessError.PARAMMETER_VALIDATION_ERROR.getErrCode());
        commonReturnType.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        return commonReturnType;
    }

    //全局异常
    @ExceptionHandler(Exception.class)
    public CommonReturnType handleException(Exception e) {
        log.error(e.getMessage());
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setCode(EmBusinessError.UNKNOW_ERROR.getErrCode());
        commonReturnType.setMessage(EmBusinessError.UNKNOW_ERROR.getErrMsg());
        return commonReturnType;
    }

    //业务异常，自己抛出
    @ExceptionHandler(BusinessException.class)
    public CommonReturnType handleBusinessException(BusinessException e) {
        log.error(e.getMessage());
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setCode(e.getErrCode());
        commonReturnType.setMessage(e.getErrMsg());
        return commonReturnType;
    }

}
